<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Authenticate extends MX_Controller {

    function __construct() {
        $this->load->model('site_role_model');
        $this->load->model('site_privilege_model');
        $this->load->model('admin_model');
        parent::__construct();
        $current_url = str_replace(BASE_URL, '', get_current_url());
        if (strstr($current_url, 'upload')) {
            return true;
        }
		$success = $this->__check_authenticate();
		if (!$success) {
			$this->st_registry->register('admin/error', 'Bạn phải đăng nhập trước khi truy cập khu vực này');
			redirect(site_url('admin/authenticate', true));
			exit();
		}
        global $has_permit;
        $has_permit = $this->__check_privileges();
    }
	
	protected function _eventLoadLayout() {
        return true;
    }
	
	private function __check_authenticate() {
        $is_logged = $this->st_registry->registry('admin/login/success');
        if (empty($is_logged)) {
            return false;
        }
		return true;
	}

    private function __check_privileges() {
        if ($this->admin_model->is_admin()) {
            return true;
        }
        $current_url = str_replace(BASE_URL, '', get_current_url());
        // If Article Permissions Then Ignore And Handle Below Layer
        if (strstr($current_url, 'admin/cms/article')) {
            return true;
        }
        $privileges = $this->admin_model->get_privileges();
        if (empty($privileges)) {
            return false;
        }
        foreach ($privileges as $privilege) {
            if (strstr($current_url, $privilege['url'])) {
                return true;
            }
        }
        return false;
    }

    private function __get_session_key() {
        $CI = & get_instance();
        return $CI->session->userdata('session_key');
    }
}
